package com.simple.structure.flyweight;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Vector;

/**
 * @author simple
 * @version 1.0
 * @date 2019-01-04 16:04
 * @since 1.0
 */
public class ConnectionPool {
    private Vector<Connection> pool;
    /**
     * 共有属性
     */
    private String url = "jdbc:mysql://localhost:3306/test";
    private String username = "root";
    private String password = "123456";
    private String driverClassName = "com.mysql.jdbc.Driver";
    private int poolSize = 100;
    private static ConnectionPool instance = null;
    Connection connection = null;

    private ConnectionPool() {
        pool = new Vector<>(poolSize);
        for (int i = 0; i < poolSize; i++) {
            try {
                Class.forName(driverClassName);
                connection = DriverManager.getConnection(url, username, password);
                pool.add(connection);
            } catch (ClassNotFoundException | SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public synchronized void release() {
        pool.add(connection);
    }

    public synchronized Connection getConnection() {
        if (pool.size() > 0) {
            Connection connection = pool.get(0);
            pool.remove(connection);
            return connection;
        } else {
            return null;
        }
    }
}
